import * as vscode from 'vscode';
import * as path from 'path';

import Executor from './utils/executor';
import WebviewMgr from './utils/webview_mgr';
import Logger from './utils/log';
import WebServer from './utils/web_server';

let webServer: WebServer | null;

export function activate(context: vscode.ExtensionContext) {
	// 注册命令
	let disposable = vscode.commands.registerCommand('auto-tools.main_page', () => {
		webServer = new WebServer('localhost', 3000);
		webServer.RegisterHandler("PushDylib", (msg)=>{
			const result = Executor.RunCmd(`echo hello world`);
			Logger.Info(`message: ${JSON.stringify(msg)}, result: ${result}`);
			Logger.Message(`message: ${JSON.stringify(msg)}, result: ${result}`);
			WebviewMgr.GetInstance().Send({type: "PushDylib", params: result});
		});

		WebviewMgr.GetInstance().Initialize(context, path.join('out', 'dist', 'main_page'));
		WebviewMgr.GetInstance().ShowWebView('index.html');
		WebviewMgr.GetInstance().RegisterHandler("PushDylib", (msg)=>{
			const result = Executor.RunCmd(`echo hello world`);
			Logger.Info(`message: ${JSON.stringify(msg)}, result: ${result}`);
			Logger.Message(`message: ${JSON.stringify(msg)}, result: ${result}`);
			WebviewMgr.GetInstance().Send({type: "PushDylib", params: result});
		});
		WebviewMgr.GetInstance().RegisterHandler("CopyFile", (msg)=>{
			Logger.Message(`message: ${JSON.stringify(msg)}`);
			WebviewMgr.GetInstance().Send({type: "CopyFile", params: "successfully"});
		});
		WebviewMgr.GetInstance().RegisterHandler("RunCmd", (msg)=>{
			const cmd = msg.params;
			const result = Executor.RunCmd(cmd);
			Logger.Message(`The command is: "${cmd}" and result is: "${result}".`);
			WebviewMgr.GetInstance().Send({type: "RunCmd", params: result});
		});
		WebviewMgr.GetInstance().RegisterHandler("RunScript", (msg)=>{
			// C:\Users\Coder\Code\BatScript\test_bat.bat
			const scriptInfo = path.parse(msg.params);
			const result = Executor.RunScript(scriptInfo["dir"], scriptInfo["base"]);
			Logger.Message(`path info: "${JSON.stringify(scriptInfo)}", and result is: "${result}"`);
			WebviewMgr.GetInstance().Send({type: "RunScript", params: result});
		});
	});
	context.subscriptions.push(disposable);
}

export function deactivate() {
	webServer?.Close();
}
